//
//  ScrollViewViewController.m
//  ScrollView
//

#import "ScrollViewViewController.h"

@implementation ScrollViewViewController

- (void)loadScrollViewWithPage:(UIView *)page {
	int pageCount = [[myScrollView subviews] count];
	
	CGRect bounds = myScrollView.bounds;
	bounds.origin.x = bounds.size.width * pageCount;
	bounds.origin.y = 0;
	page.frame = bounds;
	[myScrollView addSubview:page];
}

- (void)createPages {
	CGRect pageRect = myScrollView.frame;
	
	// 페이지 생성
	UIView *page1 = [[UIView alloc] initWithFrame:pageRect];
	page1.backgroundColor = [UIColor blueColor];
	UIView *page2 = [[UIView alloc] initWithFrame:pageRect];
	page2.backgroundColor = [UIColor redColor];
	UIView *page3 = [[UIView alloc] initWithFrame:pageRect];
	page3.backgroundColor = [UIColor greenColor];
	
	// 스크롤뷰에 추가
	[self loadScrollViewWithPage:page1];
	[self loadScrollViewWithPage:page2];
	[self loadScrollViewWithPage:page3];
	
	// 정리
	[page1 release];
	[page2 release];
	[page3 release];
}

- (void)viewDidLoad {
    [super viewDidLoad];
	
	float pageControlHeight = 18.0;
	int pageCount = 3;
	
	CGRect scrollViewRect = [self.view bounds];
	scrollViewRect.size.height -= pageControlHeight;

	// 스크롤뷰 생성
	myScrollView = [[UIScrollView alloc] initWithFrame:scrollViewRect];
	myScrollView.pagingEnabled = YES;
	
	myScrollView.contentSize = CGSizeMake(scrollViewRect.size.width
										  * pageCount, 1);
	myScrollView.showsHorizontalScrollIndicator = NO;
	myScrollView.showsVerticalScrollIndicator = NO;
	myScrollView.delegate = self;

	// 페이징 객체 생성
	CGRect pageViewRect = [self.view bounds];
	pageViewRect.size.height = pageControlHeight;
	pageViewRect.origin.y = scrollViewRect.size.height;
	
	myPageControl = [[UIPageControl alloc] initWithFrame:pageViewRect];
	myPageControl.backgroundColor = [UIColor blackColor];
	myPageControl.numberOfPages = pageCount;
	myPageControl.currentPage = 0;
	[myPageControl addTarget:self
					  action:@selector(changePage:)
			forControlEvents:UIControlEventValueChanged];
	
	// 페이지 생성
	[self createPages];
	
	// 배경 뷰에 붙임
	[self.view addSubview:myScrollView];
	[self.view addSubview:myPageControl];
	
	// 정리
	[myPageControl release];
	[myScrollView release];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
	CGFloat pageWidth = scrollView.frame.size.width;
	int page = floor((scrollView.contentOffset.x - pageWidth / 2)
					 / pageWidth) + 1;
	myPageControl.currentPage = page;
}

- (void)changePage:(id)sender {
	int page = myPageControl.currentPage;
	
	// 지정된 페이지로 스크롤 뷰의 내용을 스크롤한다.
	CGRect frame = myScrollView.frame;
	frame.origin.x = frame.size.width * page;
	frame.origin.y = 0;
	[myScrollView scrollRectToVisible:frame animated:YES];
}

- (void)dealloc {
    [super dealloc];
}

@end
